<template>
  <div class="nav-bar">
    <!-- <Icon
      @click="onBack"
      icon="iconoir:nav-arrow-left"
      size="20"
      style="position: absolute; left: 0"
    /> -->
    <span>电子签名</span>
  </div>

  <div class="tips">请在空白区域内容进行签名，注意笔画工整</div>
  <canvas id="canvas" width="400" height="200"></canvas>

  <button @click="onClear" class="common-button-weak btn" style="bottom: 135px">重写</button>
  <button @click="saveCanvas" class="common-button-main btn" style="bottom: 36px">确认提交</button>
</template>

<script lang="ts" setup>
  // import Icon from '/@/components/Icon/index';
  import { onMounted, unref } from 'vue';
  import { uploadForWorkItemApi, saveWorkItemSignInfoApi } from '../../../api/flow/flow';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';

  const { createMessage } = useMessage();
  const { currentRoute } = useRouter();
  const route: any = unref(currentRoute);
  let canvas;
  let ctx;
  let isDrawing = false;
  let lastX = 0;
  let lastY = 0;

  onMounted(() => {
    canvas = document.getElementById('canvas');
    canvas.height = window.innerHeight - 44;
    canvas.width = window.innerWidth;
    ctx = canvas.getContext('2d');
    canvas.addEventListener('touchstart', startDrawing);
    canvas.addEventListener('touchmove', draw);
    canvas.addEventListener('touchend', stopDrawing);
  });

  const draw = (e) => {
    e.preventDefault();
    if (!isDrawing) return;
    const { clientX, clientY } = e.targetTouches[0];
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(clientX, clientY);
    ctx.stroke();
    [lastX, lastY] = [clientX, clientY];
  };

  const startDrawing = (e) => {
    const { clientX, clientY } = e.targetTouches[0];
    e.preventDefault();
    isDrawing = true;
    [lastX, lastY] = [clientX, clientY];
  };

  const stopDrawing = () => {
    isDrawing = false;
  };

  const onClear = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  };

  const saveCanvas = () => {
    let hide;
    const image = canvas.toDataURL();

    rotateBase64Img(image, 270, async (base64data) => {
      try {
        const file = dataURLtoFile(base64data, 'signatureImg.jpg');
        const uploadApiParams = {
          data: {
            guid: route.query.guid,
          },
          file,
        };

        hide = createMessage.loading('提交中', 0);
        const url = await uploadForWorkItemApi(uploadApiParams);
        route.query.sign = {
          url,
        };
        await saveWorkItemSignInfoApi(route.query);
        setTimeout(hide, 0);
        createMessage.success(`签名保存成功，当前页面可关闭`);
        // createConfirm({
        //   iconType: 'success',
        //   title: '提示',
        //   content: `签名保存成功`,
        //   onOk: async () => {
        //     window.opener = null;
        //     window.open('', '_self');
        //     window.close();
        //   },
        // });
      } catch (e) {
        setTimeout(hide, 0);
        createMessage.error(`保存失败${e}`);
      }
    });
  };

  //签完名的图片旋转处理
  const rotateBase64Img = (src, edg, callback) => {
    let canvas = document.createElement('canvas');
    let ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
    let imgW; //图片宽度
    let imgH; //图片高度
    let size; //canvas初始大小
    if (edg % 90 != 0) {
      console.error('旋转角度必须是90的倍数!');
      throw '旋转角度必须是90的倍数!';
    }
    edg < 0 && (edg = (edg % 360) + 360);
    const quadrant = (edg / 90) % 4; //旋转象限
    const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; //裁剪坐标
    let image = new Image();
    image.crossOrigin = 'anonymous';
    image.src = src;
    image.onload = () => {
      imgW = image.width;
      imgH = image.height;
      size = imgW > imgH ? imgW : imgH;
      canvas.width = size * 2;
      canvas.height = size * 2;
      switch (quadrant) {
        case 0:
          cutCoor.sx = size;
          cutCoor.sy = size;
          cutCoor.ex = size + imgW;
          cutCoor.ey = size + imgH;
          break;
        case 1:
          cutCoor.sx = size - imgH;
          cutCoor.sy = size;
          cutCoor.ex = size;
          cutCoor.ey = size + imgW;
          break;
        case 2:
          cutCoor.sx = size - imgW;
          cutCoor.sy = size - imgH;
          cutCoor.ex = size;
          cutCoor.ey = size;
          break;
        case 3:
          cutCoor.sx = size;
          cutCoor.sy = size - imgW;
          cutCoor.ex = size + imgH;
          cutCoor.ey = size + imgW;
          break;
      }
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx?.translate(size, size);
      ctx?.rotate((edg * Math.PI) / 180);
      //drawImage向画布上绘制图片
      ctx?.drawImage(image, 0, 0);
      //getImageData() 复制画布上指定矩形的像素数据
      let imgData = ctx!.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
      if (quadrant % 2 == 0) {
        canvas.width = imgW;
        canvas.height = imgH;
      } else {
        canvas.width = imgH;
        canvas.height = imgW;
      }
      //putImageData() 将图像数据放回画布
      ctx?.putImageData(imgData, 0, 0);
      callback(canvas.toDataURL('image/jpeg'));
    };
  };
  //先将base64转换为blob
  const dataURLtoFile = (dataurl, fileName) => {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    const blob: any = new Blob([u8arr], { type: mime });

    blob.lastModifiedDate = new Date(); // 文件最后的修改日期
    blob.name = fileName; // 文件名
    return new File([blob], fileName, { type: blob.type, lastModified: Date.now() });
  };

  // const onBack = () => {
  //   window.history.back();
  // };
</script>
<style lang="scss" scoped>
  .nav-bar {
    height: 44px;
    display: flex;
    font-size: 14px;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
  }
  .tips {
    position: fixed;
    right: -120px;
    top: 250px;
    color: rgba(0, 0, 0, 0.5);
    transform: rotate(90deg);
  }
  /* 主按钮 */
  .common-button-main {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    text-align: center;
    color: #fff;
    background: #1153d8;
    border-radius: 4px;
  }
  /* 弱按钮 */
  .common-button-weak {
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 40px;
    font-size: 16px;
    text-align: center;
    color: #1153d8;
    border-radius: 4px;
    border: 1px solid #1153d8;
  }
  .btn {
    position: fixed;
    left: -8px;
    width: 88px;
    height: 32px;
    font-size: 14px;
    transform: rotate(90deg);
  }
</style>
